<template>
  <div class="home-container">
    <!-- 导航 -->
    <div class="navbar-container">
      <navbar @restart-success="refreshData" />
    </div>
    
    <div class="content-container">
      <!-- 第一行：同步信息卡片 -->
      <el-row :gutter="20" class="card-row">
        <!-- GRAS3 -->
        <el-col :span="8">
          <el-card class="sync-card" shadow="hover" :class="{'offline-card': !gras3Online}">
            <div class="card-header">
              <span class="card-title">GRAS3</span>
              <div class="card-header-extra">
                <span class="sync-file-info" :title="gras3RealSync">{{ gras3RealSync }}</span>
                <el-tag v-if="!gras3Online" type="danger" class="offline-tag" effect="dark">网络异常</el-tag>
              </div>
            </div>
            <div class="card-body">
              <el-row>
                <el-col :span="4" class="sync-info">
                  <el-row class="status-tag">
                    <el-tag type="success" size="medium"
                      :class="{'status-tag-highlight': gras3Stats.DONE > 0, 'status-tag-dim': !gras3Stats.DONE}"
                      :style="gras3Stats.DONE > 0 ? '' : 'pointer-events: none; cursor: default;'"
                      @click="gras3Stats.DONE > 0 ? showStatusDetails('DONE', 'GRAS3', gras3Stats.DONE || 0) : null"
                    >完成: {{ gras3Stats.DONE || 0 }}</el-tag>
                  </el-row>
                  <el-row class="status-tag">
                    <el-tag type="danger" size="medium"
                      :class="{'status-tag-highlight': gras3Stats.ERROR > 0, 'status-tag-dim': !gras3Stats.ERROR}"
                      :style="gras3Stats.ERROR > 0 ? '' : 'pointer-events: none; cursor: default;'"
                      @click="gras3Stats.ERROR > 0 ? showStatusDetails('ERROR', 'GRAS3', gras3Stats.ERROR || 0) : null"
                    >错误: {{ gras3Stats.ERROR || 0 }}</el-tag>
                  </el-row>
                  <el-row class="status-tag">
                    <el-tag type="warning" size="medium"
                      :class="{'status-tag-highlight': gras3Stats.WAIT > 0, 'status-tag-dim': !gras3Stats.WAIT}"
                      :style="gras3Stats.WAIT > 0 ? '' : 'pointer-events: none; cursor: default;'"
                      @click="gras3Stats.WAIT > 0 ? showStatusDetails('WAIT', 'GRAS3', gras3Stats.WAIT || 0) : null"
                    >等待: {{ gras3Stats.WAIT || 0 }}</el-tag>
                  </el-row>
                  <el-row class="status-tag">
                    <el-tag type="info" size="medium"
                      :class="{'status-tag-highlight': (gras3Retransmission && gras3Retransmission.t > 0), 'status-tag-dim': !(gras3Retransmission && gras3Retransmission.t > 0)}"
                      :style="(gras3Retransmission && gras3Retransmission.t > 0) ? '' : 'pointer-events: none; cursor: default;'"
                      @click="(gras3Retransmission && gras3Retransmission.t > 0) ? showRetransmissionDetails('GRAS3', gras3Retransmission || {dt:0,t:0}) : null"
                    >重传: {{ (gras3Retransmission && gras3Retransmission.t) || 0 }}/{{ (gras3Retransmission && gras3Retransmission.t) || 0 }}</el-tag>
                  </el-row>
                </el-col>
                <el-col :span="20" class="gauge-container">
                  <div id="echartsGras3" class="gauge-chart"></div>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </el-col>
        
        <!-- GRAS4 -->
        <el-col :span="8">
          <el-card class="sync-card" shadow="hover" :class="{'offline-card': !gras4Online}">
            <div class="card-header">
              <span class="card-title">GRAS4</span>
              <div class="card-header-extra">
                <span class="sync-file-info" :title="gras4RealSync">{{ gras4RealSync }}</span>
                <el-tag v-if="!gras4Online" type="danger" class="offline-tag" effect="dark">网络异常</el-tag>
              </div>
            </div>
            <div class="card-body">
              <el-row>
                <el-col :span="4" class="sync-info">
                  <el-row class="status-tag">
                    <el-tag type="success" size="medium"
                      :class="{'status-tag-highlight': gras4Stats.DONE > 0, 'status-tag-dim': !gras4Stats.DONE}"
                      :style="gras4Stats.DONE > 0 ? '' : 'pointer-events: none; cursor: default;'"
                      @click="gras4Stats.DONE > 0 ? showStatusDetails('DONE', 'GRAS4', gras4Stats.DONE || 0) : null"
                    >完成: {{ gras4Stats.DONE || 0 }}</el-tag>
                  </el-row>
                  <el-row class="status-tag">
                    <el-tag type="danger" size="medium"
                      :class="{'status-tag-highlight': gras4Stats.ERROR > 0, 'status-tag-dim': !gras4Stats.ERROR}"
                      :style="gras4Stats.ERROR > 0 ? '' : 'pointer-events: none; cursor: default;'"
                      @click="gras4Stats.ERROR > 0 ? showStatusDetails('ERROR', 'GRAS4', gras4Stats.ERROR || 0) : null"
                    >错误: {{ gras4Stats.ERROR || 0 }}</el-tag>
                  </el-row>
                  <el-row class="status-tag">
                    <el-tag type="warning" size="medium"
                      :class="{'status-tag-highlight': gras4Stats.WAIT > 0, 'status-tag-dim': !gras4Stats.WAIT}"
                      :style="gras4Stats.WAIT > 0 ? '' : 'pointer-events: none; cursor: default;'"
                      @click="gras4Stats.WAIT > 0 ? showStatusDetails('WAIT', 'GRAS4', gras4Stats.WAIT || 0) : null"
                    >等待: {{ gras4Stats.WAIT || 0 }}</el-tag>
                  </el-row>
                  <el-row class="status-tag">
                    <el-tag type="info" size="medium"
                      :class="{'status-tag-highlight': (gras4Retransmission && gras4Retransmission.t > 0), 'status-tag-dim': !(gras4Retransmission && gras4Retransmission.t > 0)}"
                      :style="(gras4Retransmission && gras4Retransmission.t > 0) ? '' : 'pointer-events: none; cursor: default;'"
                      @click="(gras4Retransmission && gras4Retransmission.t > 0) ? showRetransmissionDetails('GRAS4', gras4Retransmission || {dt:0,t:0}) : null"
                    >重传: {{ (gras4Retransmission && gras4Retransmission.t) || 0 }}/{{ (gras4Retransmission && gras4Retransmission.t) || 0 }}</el-tag>
                  </el-row>
                </el-col>
                <el-col :span="20" class="gauge-container">
                  <div id="echartsGras4" class="gauge-chart"></div>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </el-col>
        
        <!-- GRAS5 -->
        <el-col :span="8">
          <el-card class="sync-card" shadow="hover" :class="{'offline-card': !gras5Online}">
            <div class="card-header">
              <span class="card-title">GRAS5</span>
              <div class="card-header-extra">
                <span class="sync-file-info" :title="gras5RealSync">{{ gras5RealSync }}</span>
                <el-tag v-if="!gras5Online" type="danger" class="offline-tag" effect="dark">网络异常</el-tag>
              </div>
            </div>
            <div class="card-body">
              <el-row>
                <el-col :span="4" class="sync-info">
                  <el-row class="status-tag">
                    <el-tag type="success" size="medium"
                      :class="{'status-tag-highlight': gras5Stats.DONE > 0, 'status-tag-dim': !gras5Stats.DONE}"
                      :style="gras5Stats.DONE > 0 ? '' : 'pointer-events: none; cursor: default;'"
                      @click="gras5Stats.DONE > 0 ? showStatusDetails('DONE', 'GRAS5', gras5Stats.DONE || 0) : null"
                    >完成: {{ gras5Stats.DONE || 0 }}</el-tag>
                  </el-row>
                  <el-row class="status-tag">
                    <el-tag type="danger" size="medium"
                      :class="{'status-tag-highlight': gras5Stats.ERROR > 0, 'status-tag-dim': !gras5Stats.ERROR}"
                      :style="gras5Stats.ERROR > 0 ? '' : 'pointer-events: none; cursor: default;'"
                      @click="gras5Stats.ERROR > 0 ? showStatusDetails('ERROR', 'GRAS5', gras5Stats.ERROR || 0) : null"
                    >错误: {{ gras5Stats.ERROR || 0 }}</el-tag>
                  </el-row>
                  <el-row class="status-tag">
                    <el-tag type="warning" size="medium"
                      :class="{'status-tag-highlight': gras5Stats.WAIT > 0, 'status-tag-dim': !gras5Stats.WAIT}"
                      :style="gras5Stats.WAIT > 0 ? '' : 'pointer-events: none; cursor: default;'"
                      @click="gras5Stats.WAIT > 0 ? showStatusDetails('WAIT', 'GRAS5', gras5Stats.WAIT || 0) : null"
                    >等待: {{ gras5Stats.WAIT || 0 }}</el-tag>
                  </el-row>
                  <el-row class="status-tag">
                    <el-tag type="info" size="medium"
                      :class="{'status-tag-highlight': (gras5Retransmission && gras5Retransmission.t > 0), 'status-tag-dim': !(gras5Retransmission && gras5Retransmission.t > 0)}"
                      :style="(gras5Retransmission && gras5Retransmission.t > 0) ? '' : 'pointer-events: none; cursor: default;'"
                      @click="(gras5Retransmission && gras5Retransmission.t > 0) ? showRetransmissionDetails('GRAS5', gras5Retransmission || {dt:0,t:0}) : null"
                    >重传: {{ (gras5Retransmission && gras5Retransmission.t) || 0 }}/{{ (gras5Retransmission && gras5Retransmission.t) || 0 }}</el-tag>
                  </el-row>
                </el-col>
                <el-col :span="20" class="gauge-container">
                  <div id="echartsGras5" class="gauge-chart"></div>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第二行：历史同步信息和磁盘空间监视/运行时间 -->
      <el-row :gutter="20" class="card-row" style="height: 35%;">
        <!-- 历史同步信息 -->
        <el-col :span="16">
          <el-card class="history-card" shadow="hover">
            <div class="card-header">
              <span class="card-title">历史同步信息</span>
              <div class="card-header-extra">
                <span class="stat-info" v-if="option.title.text">{{ option.title.text }}</span>
                <span class="stat-info sub-info" v-if="option.title.subtext">{{ option.title.subtext }}</span>
                <el-button type="primary" size="small" style="margin-left: 15px;" @click="showSyncDetails">查看更多</el-button>
              </div>
            </div>
            <div class="card-body">
              <div class="filter-options">
                <el-row type="flex" justify="space-between" align="middle">
                  <el-col :span="8">
                    <el-radio-group v-model="radio4" size="medium" @input="get_file_stat()">
                      <el-radio-button label="0">全部</el-radio-button>
                      <el-radio-button label="GRAS3">GRAS3</el-radio-button>
                      <el-radio-button label="GRAS4">GRAS4</el-radio-button>
                      <el-radio-button label="GRAS5">GRAS5</el-radio-button>
                    </el-radio-group>
                  </el-col>
                  <el-col :span="16" style="text-align: right;">
                    <el-date-picker v-model="value1" type="daterange" size="medium" range-separator="至"
                      start-placeholder="开始日期" end-placeholder="结束日期" @change="get_file_stat()" :picker-options="pickerOptions">
                    </el-date-picker>
                  </el-col>
                </el-row>
              </div>
              <div id="echarts" class="history-chart"></div>
            </div>
          </el-card>
        </el-col>
        
        <!-- 磁盘空间监视和运行时间 -->
        <el-col :span="8">
          <!-- 磁盘空间监视 -->
          <el-card class="disk-card" shadow="hover">
            <div class="card-header">
              <span class="card-title">磁盘空间监视</span>
            </div>
            <div class="card-body">
              <el-row :gutter="15" class="disk-row">
                <el-col :span="8" class="disk-col">
                  <div class="disk-label">密云站：{{ mycppath }}</div>
                  <el-progress type="dashboard" :percentage="mycpkj" :color="colors"></el-progress>
                  <el-button type="primary" size="small" class="clean-btn" 
                    :class="{'clean-btn-disabled': mycpkj < 90}"
                    @click="handleCleanClick('密云站', mycpkj)">清理</el-button>
                </el-col>
                <el-col :span="8" class="disk-col">
                  <div class="disk-label">武清站：{{ wqcppath }}</div>
                  <el-progress type="dashboard" :percentage="wqcpkj" :color="colors"></el-progress>
                  <el-button type="primary" size="small" class="clean-btn" 
                    :class="{'clean-btn-disabled': wqcpkj < 90}"
                    @click="handleCleanClick('武清站', wqcpkj)">清理</el-button>
                </el-col>
                <el-col :span="8" class="disk-col">
                  <div class="disk-label">总部：{{ zbcppath }}</div>
                  <el-progress type="dashboard" :percentage="zbcpkj" :color="colors"></el-progress>
                  <el-button type="primary" size="small" class="clean-btn" 
                    :class="{'clean-btn-disabled': zbcpkj < 90}"
                    @click="handleCleanClick('总部', zbcpkj)">清理</el-button>
                </el-col>
              </el-row>
            </div>
          </el-card>
          
          <!-- 运行总时长 -->
          <el-card class="time-card" shadow="hover" style="margin-top: 20px;">
            <div class="card-header">
              <span class="card-title">运行总时长</span>
            </div>
            <div class="card-body">
              <el-row type="flex" justify="center" class="time-display">
                <!-- 小时部分 -->
                <template v-if="H >= 100">
                  <el-col :span="7" class="time-block">
                    <div class="time-value">
                      <span class="time-digit">{{ Math.floor(H / 100) }}</span>
                      <span class="time-digit">{{ Math.floor((H % 100) / 10) }}</span>
                      <span class="time-digit">{{ H % 10 }}</span>
                    </div>
                    <div class="time-label">时</div>
                  </el-col>
                </template>
                <template v-else>
                  <el-col :span="7" class="time-block">
                    <div class="time-value">
                      <span class="time-digit">{{ Math.floor(H / 10) }}</span>
                      <span class="time-digit">{{ H % 10 }}</span>
                    </div>
                    <div class="time-label">时</div>
                  </el-col>
                </template>
                <span class="time-separator">:</span>
                <el-col :span="7" class="time-block">
                  <div class="time-value">
                    <span class="time-digit">{{ Math.floor(M / 10) }}</span>
                    <span class="time-digit">{{ M % 10 }}</span>
                  </div>
                  <div class="time-label">分</div>
                </el-col>
                <span class="time-separator">:</span>
                <el-col :span="7" class="time-block">
                  <div class="time-value">
                    <span class="time-digit">{{ Math.floor(S / 10) }}</span>
                    <span class="time-digit">{{ S % 10 }}</span>
                  </div>
                  <div class="time-label">秒</div>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 添加同步详情对话框 -->
    <el-dialog
      title="历史同步详情"
      :visible.sync="syncDetailsDialogVisible"
      width="85%"
      top="5vh"
      :before-close="() => syncDetailsDialogVisible = false"
      class="sync-details-dialog"
    >
      <div class="filter-bar">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-radio-group v-model="syncDetailsStationFilter" size="small" @change="handleSyncDetailsStationChange">
              <el-radio-button label="0">全部</el-radio-button>
              <el-radio-button label="GRAS3">GRAS3</el-radio-button>
              <el-radio-button label="GRAS4">GRAS4</el-radio-button>
              <el-radio-button label="GRAS5">GRAS5</el-radio-button>
            </el-radio-group>
          </el-col>
          <el-col :span="16" style="text-align: right;">
            <el-date-picker
              v-model="syncDetailsDateRange"
              type="daterange"
              size="small"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleSyncDetailsDateChange"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-col>
        </el-row>
      </div>
      
      <el-table
        :data="syncDetailsData"
        style="width: 100%"
        border
        v-loading="syncDetailsLoading"
        max-height="600"
        size="small"
        @sort-change="handleSyncDetailsSortChange"
      >
        <el-table-column prop="fid" label="序号" width="60">
          <template slot-scope="scope">
            {{ (syncDetailsPagination.currentPage - 1) * syncDetailsPagination.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="fileName" label="同步文件" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="to_path" label="目标目录" min-width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.to_path || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="同步时间" width="150">
          <template slot-scope="scope">
            {{ scope.row.copyDoneTime || scope.row.ctime || '--' }}
          </template>
        </el-table-column>
        <el-table-column 
          prop="status"
          label="结果" 
          width="80"
          sortable="custom"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'DONE' ? 'success' : scope.row.status === 'FAIL' ? 'danger' : 'warning'" size="mini">
              {{ formatSyncStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="异常时间" width="150">
          <template slot-scope="scope">
            {{ scope.row.status === 'ERROR' ? (scope.row.utime || '--') : '--' }}
          </template>
        </el-table-column>
        <el-table-column label="站点" width="80">
          <template slot-scope="scope">
            {{ formatStationName(scope.row.station) }}
          </template>
        </el-table-column>
        <el-table-column label="异常原因" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.status === 'ERROR' ? (scope.row.err_log || '--') : '--' }}
          </template>
        </el-table-column>
        <el-table-column label="大小" width="100">
          <template slot-scope="scope">
            {{ formatFileSize(scope.row.fileSize) }}
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSyncDetailsSizeChange"
          @current-change="handleSyncDetailsPageChange"
          :current-page="syncDetailsPagination.currentPage"
          :page-sizes="[20, 50, 100, 200]"
          :page-size="syncDetailsPagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="syncDetailsPagination.total"
        ></el-pagination>
      </div>
    </el-dialog>

    <!-- 添加GRAS3图表放大对话框 -->
    <el-dialog
      title="GRAS3实时同步速度"
      :visible.sync="chartGras3DialogVisible"
      width="80%"
      :before-close="() => chartGras3DialogVisible = false"
      class="chart-dialog"
    >
      <div id="echartsGras3-large" style="height: 600px;"></div>
    </el-dialog>

    <!-- 添加GRAS4图表放大对话框 -->
    <el-dialog
      title="GRAS4实时同步速度"
      :visible.sync="chartGras4DialogVisible"
      width="80%"
      :before-close="() => chartGras4DialogVisible = false"
      class="chart-dialog"
    >
      <div id="echartsGras4-large" style="height: 600px;"></div>
    </el-dialog>

    <!-- 添加GRAS5图表放大对话框 -->
    <el-dialog
      title="GRAS5实时同步速度"
      :visible.sync="chartGras5DialogVisible"
      width="80%"
      :before-close="() => chartGras5DialogVisible = false"
      class="chart-dialog"
    >
      <div id="echartsGras5-large" style="height: 600px;"></div>
    </el-dialog>

    <!-- 添加状态详情对话框 -->
    <el-dialog
      :title="statusDialogTitle"
      :visible.sync="statusDetailsDialogVisible"
      width="85%"
      top="5vh"
      :before-close="() => statusDetailsDialogVisible = false"
      class="sync-details-dialog"
    >
      <!-- 新增：等待文件清理按钮，仅在"等待"状态时显示 -->
      <div class="dialog-header-actions" v-if="statusDetailsDialogVisible && getCurrentStatusFromTitle() && getCurrentStatusFromTitle().status === 'WAIT'">
        <el-button
          type="danger"
          size="small"
          @click="handleCleanWaitList"
          :disabled="!statusDetailsData.length"
        >清理等待列表</el-button>
      </div>
      <el-table
        :data="statusDetailsData"
        style="width: 100%"
        border
        v-loading="statusDetailsLoading"
        max-height="600"
        size="small"
      >
        <el-table-column prop="fid" label="序号" width="60">
          <template slot-scope="scope">
            {{ (statusDetailsPagination.currentPage - 1) * statusDetailsPagination.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="fileName" label="同步文件" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="to_path" label="目标目录" min-width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.to_path || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="同步时间" width="150">
          <template slot-scope="scope">
            {{ scope.row.copyDoneTime || scope.row.ctime || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="结果" width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'DONE' ? 'success' : scope.row.status === 'FAIL' ? 'danger' : 'warning'" size="mini">
              {{ formatSyncStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="异常时间" width="150">
          <template slot-scope="scope">
            {{ scope.row.status === 'ERROR' ? (scope.row.utime || '--') : '--' }}
          </template>
        </el-table-column>
        <el-table-column label="站点" width="80">
          <template slot-scope="scope">
            {{ formatStationName(scope.row.station) }}
          </template>
        </el-table-column>
        <el-table-column label="异常原因" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.status === 'ERROR' ? (scope.row.err_log || '--') : '--' }}
          </template>
        </el-table-column>
        <el-table-column label="大小" width="100">
          <template slot-scope="scope">
            {{ formatFileSize(scope.row.fileSize) }}
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleStatusDetailsSizeChange"
          @current-change="handleStatusDetailsPageChange"
          :current-page="statusDetailsPagination.currentPage"
          :page-sizes="[20, 50, 100, 200]"
          :page-size="statusDetailsPagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="statusDetailsPagination.total"
        ></el-pagination>
      </div>
    </el-dialog>

    <!-- 添加重传文件列表对话框 -->
    <el-dialog
      :title="retransmissionDialogTitle"
      :visible.sync="retransmissionDialogVisible"
      width="85%"
      top="5vh"
      :before-close="() => retransmissionDialogVisible = false"
      class="sync-details-dialog"
    >
      <div class="dialog-header-actions">
        <el-button 
          type="danger" 
          size="small" 
          @click="handleCleanRetransmission"
          :disabled="!retransmissionData.length"
        >清理重传列表</el-button>
      </div>
      <el-table
        :data="retransmissionData"
        style="width: 100%"
        border
        v-loading="retransmissionLoading"
        max-height="600"
        size="small"
      >
        <el-table-column prop="fid" label="序号" width="60">
          <template slot-scope="scope">
            {{ (retransmissionPagination.currentPage - 1) * retransmissionPagination.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="fileName" label="文件名" min-width="280" show-overflow-tooltip></el-table-column>
        <el-table-column prop="to_path" label="目标目录" min-width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.to_path || '--' }}
          </template>
        </el-table-column>
        <!-- 移除重传时间列 -->
        <el-table-column label="状态" width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'DONE' ? 'success' : 'warning'" size="mini">
              {{ formatSyncStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="天线" width="80">
          <template slot-scope="scope">
            {{ scope.row.gras }}
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleRetransmissionSizeChange"
          @current-change="handleRetransmissionPageChange"
          :current-page="retransmissionPagination.currentPage"
          :page-sizes="[20, 50, 100, 200]"
          :page-size="retransmissionPagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="retransmissionPagination.total"
        ></el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
import * as echarts from 'echarts';
import config from "@/utils/config";
const { DMSip } = config;
import { checkPermission } from "../utils/auth";

// 设置moment为中文
moment.locale('zh-cn');

export default {
  data() {
    return {
      syncDetailsSortCol: '',   // 当前排序字段
      syncDetailsSortOrder: '', // 当前排序方式
      // 添加速度历史数据数组
      gras3SpeedHistory: [],
      gras4SpeedHistory: [],
      gras5SpeedHistory: [],
      gras3TimeHistory: [], // 添加GRAS3时间历史数组
      gras4TimeHistory: [], // 添加GRAS4时间历史数组
      gras5TimeHistory: [], // 添加GRAS5时间历史数组
      maxSpeedPoints: 30, // 保存30个数据点
      // option配置
      option: {
        color: ['#eab760', '#6db049', '#f56c6c'], // 添加红色
        title: {
          text: '',
          subtext: '',
          right: '5%',
          top: '0%',
          textStyle: {
            fontSize: 14
          },
          subtextStyle: {
            fontSize: 14,
            color: '#666'
          },
          show: false
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          textStyle: {
            fontSize: 20,
          },
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            inside: false,
            textStyle: {
              fontSize: '14',
              itemSize: ''
            }
          },
        },
        yAxis: [
          {
            type: 'value',
            name: '数据量(GB)',
            min: 0,
            position: 'left',
            axisLabel: {
              formatter: '{value} GB',
              textStyle: {
                fontSize: '14',
                itemSize: ''
              }
            }
          },
          {
            type: 'value',
            name: '文件数/异常数',
            min: 0,
            position: 'right',
            axisLabel: {
              formatter: '{value} 个',
              textStyle: {
                fontSize: '14',
                itemSize: ''
              }
            }
          }
        ],
        series: [
          {
            name: '数据量',
            type: 'bar',
            data: [],
            label: {
              show: true,
              position: 'top',
              formatter: function(params) {
                return params.value > 0 ? params.value.toFixed(2) : '';
              },
              fontSize: 12,
              color: '#606266'
            },
            yAxisIndex: 0
          },
          {
            name: '文件数',
            type: 'bar',
            data: [],
            label: {
              show: true,
              position: 'top',
              formatter: function(params) {
                return params.value > 0 ? params.value : '';
              },
              fontSize: 12,
              color: '#606266'
            },
            yAxisIndex: 1
          },
          {
            name: '异常数',
            type: 'bar',
            data: [],
            label: {
              show: true,
              position: 'top',
              formatter: function(params) {
                return params.value > 0 ? params.value : '';
              },
              fontSize: 12,
              color: '#606266'
            },
            yAxisIndex: 1
          }
        ]
      },
      value1: [
        moment().subtract(6, 'days').toDate(), // 7天前
        moment().toDate() // 当前时间
      ],
      // 日期
      pickerOptions: {
        disabledDate: time => {
          return time.getTime() > Date.now() + 0 * 24 * 60 * 60 * 1000
        },
        shortcuts: [{
          text: '最近7天',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      colors: [
        { color: '#5cb87a', percentage: 50 },   // 绿色，0~50%
        { color: '#e6a23c', percentage: 90 },   // 橙色，50%~90%
        { color: '#f56c6c', percentage: 100 }   // 红色，90%~100%
      ],
      radio4: '0',
      option1: {
        grid: {
          top: 30,
          left: 50,
          right: 20,
          bottom: 30
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `${params[0].axisValue}<br/>传输速度: ${params[0].value} MB/s`;
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: new Array(30).fill(''),
          axisLabel: {
            show: true,
            interval: 5,
            formatter: function(value) {
              return value ? value.substring(11, 19) : ''; // 只显示时分秒
            }
          }
        },
        yAxis: {
          type: 'value',
          name: 'MB/s',
          min: 0,
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [{
          name: '传输速度',
          type: 'line',
          smooth: true,
          symbol: 'none',
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: 'rgba(58, 77, 233, 0.3)'
              }, {
                offset: 1,
                color: 'rgba(58, 77, 233, 0.1)'
              }]
            }
          },
          itemStyle: {
            color: '#3a4de9'
          },
          data: new Array(30).fill(0)
        }]
      },
      option2: {
        grid: {
          top: 30,
          left: 50,
          right: 20,
          bottom: 30
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `${params[0].axisValue}<br/>传输速度: ${params[0].value} MB/s`;
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: new Array(30).fill(''),
          axisLabel: {
            show: true,
            interval: 5,
            formatter: function(value) {
              return value ? value.substring(11, 19) : ''; // 只显示时分秒
            }
          }
        },
        yAxis: {
          type: 'value',
          name: 'MB/s',
          min: 0,
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [{
          name: '传输速度',
          type: 'line',
          smooth: true,
          symbol: 'none',
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: 'rgba(58, 77, 233, 0.3)'
              }, {
                offset: 1,
                color: 'rgba(58, 77, 233, 0.1)'
              }]
            }
          },
          itemStyle: {
            color: '#3a4de9'
          },
          data: new Array(30).fill(0)
        }]
      },
      //磁盘空间
      mycppath: '',
      mycpkj: 0,
      wqcppath: '',
      wqcpkj: 0,
      zbcppath: '',
      zbcpkj: 0,
      //实时同步信息
      gras3PendingCount: 0,
      gras4PendingCount: 0,
      gras5PendingCount: 0,
      gras3RealSync: '', // 添加GRAS3当前同步文件
      gras4RealSync: '', // 添加GRAS4当前同步文件
      gras5RealSync: '', // 添加GRAS5当前同步文件
      gras3IsSyncing: false, // GRAS3是否正在同步
      gras4IsSyncing: false, // GRAS4是否正在同步
      gras5IsSyncing: false, // GRAS5是否正在同步
      gras3SyncProgress: 0,
      gras4SyncProgress: 0,
      gras5SyncProgress: 0,
      gras3Stats: {},
      gras4Stats: {},
      gras5Stats: {},
      // 历史同步详情对话框
      syncDetailsDialogVisible: false,
      syncDetailsData: [],
      syncDetailsPagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      syncDetailsLoading: false,
      syncDetailsStationFilter: '0',
      syncDetailsDateRange: [],
      // 图表对话框状态
      chartGras3DialogVisible: false,
      chartGras4DialogVisible: false,
      chartGras5DialogVisible: false,
      chartGras3Large: null,
      chartGras4Large: null,
      chartGras5Large: null,
      myChartGras3: null,
      myChartGras4: null,
      myChartGras5: null,
      
      // 图表配置
      optionGras3: {
        grid: {
          top: 40,
          left: 60,
          right: 30,
          bottom: 40
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `${params[0].axisValue}<br/>
                    <span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:#5470c6;"></span>
                    传输速度: <span style="font-weight:bold;color:#5470c6">${params[0].value} MB/s</span>`;
          },
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#5470c6',
          borderWidth: 1,
          textStyle: {
            color: '#333',
            fontSize: 14
          },
          padding: 10,
          axisPointer: {
            type: 'line',
            lineStyle: {
              color: 'rgba(84, 112, 198, 0.5)',
              width: 2
            }
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: new Array(30).fill(''),
          axisLabel: {
            show: true,
            interval: 5,
            formatter: function(value) {
              return value ? value.substring(11, 19) : ''; // 只显示时分秒
            },
            color: '#666',
            fontSize: 12
          },
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: 'MB/s',
          nameTextStyle: {
            color: '#666',
            fontSize: 13,
            padding: [0, 0, 5, 0]
          },
          min: 0,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#eee'
            }
          },
          axisLabel: {
            color: '#666',
            fontSize: 12
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        },
        series: [{
          name: '传输速度',
          type: 'line',
          smooth: true,
          symbol: 'emptyCircle',
          symbolSize: 6,
          showSymbol: false,
          emphasis: {
            scale: true,
            focus: 'series',
            itemStyle: {
              borderWidth: 2,
              shadowBlur: 10,
              shadowColor: 'rgba(84, 112, 198, 0.5)'
            }
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: 'rgba(84, 112, 198, 0.5)'
              }, {
                offset: 0.8,
                color: 'rgba(84, 112, 198, 0.1)'
              }, {
                offset: 1,
                color: 'rgba(84, 112, 198, 0.0)'
              }]
            },
            shadowColor: 'rgba(84, 112, 198, 0.2)',
            shadowBlur: 10
          },
          itemStyle: {
            color: '#5470c6',
            borderWidth: 2
          },
          lineStyle: {
            width: 3,
            shadowColor: 'rgba(84, 112, 198, 0.3)',
            shadowBlur: 10
          },
          data: new Array(30).fill(0),
          z: 10
        }],
        animation: true,
        animationDuration: 1000,
        animationEasing: 'cubicOut'
      },
      optionGras4: {
        grid: {
          top: 40,
          left: 60,
          right: 30,
          bottom: 40
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `${params[0].axisValue}<br/>
                    <span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:#91cc75;"></span>
                    传输速度: <span style="font-weight:bold;color:#91cc75">${params[0].value} MB/s</span>`;
          },
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#91cc75',
          borderWidth: 1,
          textStyle: {
            color: '#333',
            fontSize: 14
          },
          padding: 10,
          axisPointer: {
            type: 'line',
            lineStyle: {
              color: 'rgba(145, 204, 117, 0.5)',
              width: 2
            }
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: new Array(30).fill(''),
          axisLabel: {
            show: true,
            interval: 5,
            formatter: function(value) {
              return value ? value.substring(11, 19) : ''; // 只显示时分秒
            },
            color: '#666',
            fontSize: 12
          },
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: 'MB/s',
          nameTextStyle: {
            color: '#666',
            fontSize: 13,
            padding: [0, 0, 5, 0]
          },
          min: 0,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#eee'
            }
          },
          axisLabel: {
            color: '#666',
            fontSize: 12
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        },
        series: [{
          name: '传输速度',
          type: 'line',
          smooth: true,
          symbol: 'emptyCircle',
          symbolSize: 6,
          showSymbol: false,
          emphasis: {
            scale: true,
            focus: 'series',
            itemStyle: {
              borderWidth: 2,
              shadowBlur: 10,
              shadowColor: 'rgba(145, 204, 117, 0.5)'
            }
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: 'rgba(145, 204, 117, 0.5)'
              }, {
                offset: 0.8,
                color: 'rgba(145, 204, 117, 0.1)'
              }, {
                offset: 1,
                color: 'rgba(145, 204, 117, 0.0)'
              }]
            },
            shadowColor: 'rgba(145, 204, 117, 0.2)',
            shadowBlur: 10
          },
          itemStyle: {
            color: '#91cc75',
            borderWidth: 2
          },
          lineStyle: {
            width: 3,
            shadowColor: 'rgba(145, 204, 117, 0.3)',
            shadowBlur: 10
          },
          data: new Array(30).fill(0),
          z: 10
        }],
        animation: true,
        animationDuration: 1000,
        animationEasing: 'cubicOut'
      },
      optionGras5: {
        grid: {
          top: 40,
          left: 60,
          right: 30,
          bottom: 40
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `${params[0].axisValue}<br/>
                    <span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:#ee6666;"></span>
                    传输速度: <span style="font-weight:bold;color:#ee6666">${params[0].value} MB/s</span>`;
          },
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#ee6666',
          borderWidth: 1,
          textStyle: {
            color: '#333',
            fontSize: 14
          },
          padding: 10,
          axisPointer: {
            type: 'line',
            lineStyle: {
              color: 'rgba(238, 102, 102, 0.5)',
              width: 2
            }
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: new Array(30).fill(''),
          axisLabel: {
            show: true,
            interval: 5,
            formatter: function(value) {
              return value ? value.substring(11, 19) : ''; // 只显示时分秒
            },
            color: '#666',
            fontSize: 12
          },
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: 'MB/s',
          nameTextStyle: {
            color: '#666',
            fontSize: 13,
            padding: [0, 0, 5, 0]
          },
          min: 0,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#eee'
            }
          },
          axisLabel: {
            color: '#666',
            fontSize: 12
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        },
        series: [{
          name: '传输速度',
          type: 'line',
          smooth: true,
          symbol: 'emptyCircle',
          symbolSize: 6,
          showSymbol: false,
          emphasis: {
            scale: true,
            focus: 'series',
            itemStyle: {
              borderWidth: 2,
              shadowBlur: 10,
              shadowColor: 'rgba(238, 102, 102, 0.5)'
            }
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: 'rgba(238, 102, 102, 0.5)'
              }, {
                offset: 0.8,
                color: 'rgba(238, 102, 102, 0.1)'
              }, {
                offset: 1,
                color: 'rgba(238, 102, 102, 0.0)'
              }]
            },
            shadowColor: 'rgba(238, 102, 102, 0.2)',
            shadowBlur: 10
          },
          itemStyle: {
            color: '#ee6666',
            borderWidth: 2
          },
          lineStyle: {
            width: 3,
            shadowColor: 'rgba(238, 102, 102, 0.3)',
            shadowBlur: 10
          },
          data: new Array(30).fill(0),
          z: 10
        }],
        animation: true,
        animationDuration: 1000,
        animationEasing: 'cubicOut'
      },
      //运行时间
      H: 0,
      M: 0,
      S: 0,
      timer: null, // 添加定时器变量
      syncTimer: null, // 添加同步信息定时器
      timeStartSeconds: 0, // 添加初始时间秒数
      timeRunning: false, // 添加时间运行状态
      elapsedSeconds: 0, // 新增：本地已用秒数
      statusDetailsDialogVisible: false,
      statusDetailsData: [],
      statusDetailsPagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      statusDetailsLoading: false,
      statusDetailsStationFilter: '0',
      statusDetailsDateRange: [],
      statusDialogTitle: '',
      // 添加重传状态数据
      gras3Retransmission: null,
      gras4Retransmission: null,
      gras5Retransmission: null,
      
      // 添加重传文件列表相关数据
      retransmissionDialogVisible: false,
      retransmissionDialogTitle: '',
      retransmissionData: [],
      retransmissionLoading: false,
      retransmissionPagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      currentRetransmissionGras: '', // 当前查看的天线
      // 新增：保存上一次历史同步数据
      lastFileStatData: null,
      timeUpdateTimer: null, // 新增：每秒更新计时器
      diskSpaceTimer: null, // 新增：磁盘空间监视定时器
      // 添加天线联网状态变量
      gras3Online: true,
      gras4Online: true,
      gras5Online: true,
      pingStatusTimer: null, // 新增：天线Ping状态定时器
      lastCheckedDate: '', // 用于跨天检测
      dateCheckTimer: null, // 日期校验定时器
      // 新增：重传总数和已完成数
      retransmissionTotal: 0,
      retransmissionDone: 0
    }
  },
  mounted() {
    this.echartsInit()
    this.initGrasCharts() // 初始化所有GRAS图表
    this.get_pro_status()
    this.timer = setInterval(() => {
      this.get_pro_status()
    }, 60000);
    this.get_hard_disk_storage()
    // 新增：每1分钟校准一次磁盘空间监视
    this.diskSpaceTimer = setInterval(() => {
      this.get_hard_disk_storage()
    }, 60000);
    this.get_sync_file()
    this.get_file_stat()
    this.syncTimer = setInterval(() => {
      this.get_sync_file()
    }, 5000);
    this.fileStatTimer = setInterval(() => {
      this.get_file_stat()
    }, 60000); // 改为60秒
    // --- 异步获取天线联网状态，不阻塞主数据 ---
    setTimeout(() => {
      this.get_ping_status()
      // 新增：每分钟获取一次天线联网状态
      this.pingStatusTimer = setInterval(() => {
        this.get_ping_status()
      }, 60000);
    }, 0)
    // 添加窗口大小变化监听器
    window.addEventListener('resize', this.handleResize, { passive: true });
    // 新增：每天零点自动校验日期，自动刷新历史同步信息
    this.lastCheckedDate = new Date().toDateString();
    this.dateCheckTimer = setInterval(() => {
      const nowDate = new Date().toDateString();
      if (nowDate !== this.lastCheckedDate) {
        // 跨天了，自动更新日期范围为最近7天
        const endDate = new Date();
        const startDate = new Date();
        startDate.setDate(endDate.getDate() - 6);
        this.value1 = [startDate, endDate];
        this.get_file_stat();
        this.lastCheckedDate = nowDate;
      }
    }, 60000); // 每分钟检查一次
  },
  beforeDestroy() {
    // 组件销毁前清理定时器
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
    if (this.syncTimer) {
      clearInterval(this.syncTimer)
      this.syncTimer = null
    }
    // 新增：清理历史同步信息定时器
    if (this.fileStatTimer) {
      clearInterval(this.fileStatTimer)
      this.fileStatTimer = null
    }

    // 新增：清理磁盘空间监视定时器
    if (this.diskSpaceTimer) {
      clearInterval(this.diskSpaceTimer)
      this.diskSpaceTimer = null
    }
    // 清理时间更新定时器
    if (this.timeUpdateTimer) {
      clearInterval(this.timeUpdateTimer)
      this.timeUpdateTimer = null
    }
    
    // 新增：清理天线联网状态定时器
    if (this.pingStatusTimer) {
      clearInterval(this.pingStatusTimer)
      this.pingStatusTimer = null
    }
    
    // 移除窗口大小变化监听器
    window.removeEventListener('resize', this.handleResize);
    
    // 清理所有图表实例
    if (this.myChart) {
      this.myChart.dispose();
      this.myChart = null;
    }
    
    if (this.myChartGras3) {
      this.myChartGras3.dispose();
      this.myChartGras3 = null;
    }
    if (this.myChartGras4) {
      this.myChartGras4.dispose();
      this.myChartGras4 = null;
    }
    if (this.myChartGras5) {
      this.myChartGras5.dispose();
      this.myChartGras5 = null;
    }
    
    if (this.chartGras3Large) {
      this.chartGras3Large.dispose();
      this.chartGras3Large = null;
    }
    if (this.chartGras4Large) {
      this.chartGras4Large.dispose();
      this.chartGras4Large = null;
    }
    if (this.chartGras5Large) {
      this.chartGras5Large.dispose();
      this.chartGras5Large = null;
    }
    // 新增：清理日期校验定时器
    if (this.dateCheckTimer) {
      clearInterval(this.dateCheckTimer);
      this.dateCheckTimer = null;
    }
  },
  methods: {
    // 当navbar组件重启进程后刷新所有数据
    refreshData() {
      this.get_pro_status()
      this.get_hard_disk_storage()
      this.get_sync_file()
      this.get_file_stat()
      this.get_ping_status() // 新增：刷新天线联网状态
      this.$message.success('数据已刷新')
    },
    //历史同步信息
    get_file_stat(t) {
      // 准备请求参数
      let params = {
        sd: '',
        ed: '',
        sta: this.radio4 == '0' ? '' : this.radio4 // 直接使用radio4的值作为sta参数
      }

      // 处理日期
      if (this.value1 && this.value1.length === 2) {
        params.sd = moment(this.value1[0]).format('YYYY-MM-DD')
        params.ed = moment(this.value1[1]).format('YYYY-MM-DD')
      } else {
        // 如果没有选择日期，使用默认日期（当前时间往前7天）
        const endDate = moment()
        const startDate = moment().subtract(6, 'days')
        params.sd = startDate.format('YYYY-MM-DD')
        params.ed = endDate.format('YYYY-MM-DD')
        // 更新日期选择器的值
        this.value1 = [startDate.toDate(), endDate.toDate()]
      }

      // 显示加载状态（只在首次加载时显示）
      let showLoading = false;
      if (!this.lastFileStatData) showLoading = true;
      let loading = null;
      let loadingTimeout = null;
      if (showLoading) {
        loading = this.$loading({
          lock: true,
          text: '正在加载历史同步信息...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        // 5秒后自动关闭loading
        loadingTimeout = setTimeout(() => {
          if (loading) loading.close();
          loading = null;
        }, 5000);
      } else {
        loading = { close: () => {} };
      }

      this.$axios({
        method: "post",
        url: DMSip + '/-/bin.preData.get_file_stat',
        data: JSON.stringify(params),
      }).then((res) => {
        if (res.data && res.data.code === 200) {
          try {
            // 生成日期范围内的所有日期
            const startDate = moment(params.sd)
            const endDate = moment(params.ed)
            const allDates = []
            const weekDays = []
            const currentDate = startDate.clone()
            
            while (currentDate.isSameOrBefore(endDate)) {
              allDates.push(currentDate.format('YYYY-MM-DD'))
              weekDays.push(currentDate.format('dddd'))
              currentDate.add(1, 'days')
            }

            // 初始化数据数组
            const series1Data = new Array(allDates.length).fill(0)
            const series2Data = new Array(allDates.length).fill(0)
            const series3Data = new Array(allDates.length).fill(0)

            // 计算总计数据
            let totalDataSize = 0
            let totalFileCount = 0
            let totalErrorCount = 0

            // 处理返回的数据
            if (Array.isArray(res.data.data)) {
              res.data.data.forEach(item => {
                if (item.cdate && item.fz !== undefined && item.fc !== undefined) {
                  const index = allDates.indexOf(item.cdate)
                  if (index !== -1) {
                    const dataSize = Number.isFinite(parseFloat(item.fz)) ? parseFloat(item.fz) : 0
                    const fileCount = Number.isFinite(parseInt(item.fc)) ? parseInt(item.fc) : 0
                    const errorCount = Number.isFinite(parseInt(item.err_fc)) ? parseInt(item.err_fc) : 0
                    series1Data[index] = dataSize
                    series2Data[index] = fileCount
                    series3Data[index] = errorCount
                    totalDataSize += dataSize
                    totalFileCount += fileCount
                    totalErrorCount += errorCount
                  }
                }
              })
            }

            // 直接更新图表数据，不进行对比
            this.option.xAxis.data = allDates.map((date, index) => {
              return `${date}\n${weekDays[index]}`
            })
            this.option.series[0].data = series1Data
            this.option.series[1].data = series2Data
            this.option.series[2].data = series3Data

            // 更新图表配置
            this.option.yAxis[0].name = '数据量(GB)'
            this.option.series[0].name = '数据量'
            this.option.series[1].name = '文件数'
            this.option.series[2].name = '异常数'

            // 更新标题显示总计信息
            let titlePrefix = this.radio4 == '0' ? '' : this.radio4
            this.option.title.text = `${titlePrefix} 总数据量：${isNaN(totalDataSize) ? 0 : totalDataSize.toFixed(2)}GB`
            this.option.title.subtext = `${titlePrefix} 总文件数：${isNaN(totalFileCount) ? 0 : totalFileCount}个，异常数：${isNaN(totalErrorCount) ? 0 : totalErrorCount}个`

            // 强制更新图表
            if (this.myChart) {
              this.myChart.setOption(this.option, true)
            }

            // 保存本次数据用于首次加载判断
            this.lastFileStatData = {
              xAxis: allDates,
              series1: series1Data,
              series2: series2Data,
              series3: series3Data,
              totalDataSize,
              totalFileCount,
              totalErrorCount
            }

          } catch (error) {
            console.error('处理数据时出错:', error)
            this.$message.error('处理数据时出错')
          }
        } else {
          this.$message.warning('没有获取到有效数据')
        }
      }).catch(error => {
        console.error('获取历史同步信息失败:', error)
        this.$message.error('获取历史同步信息失败')
      }).finally(() => {
        if (loading) loading.close();
        if (loadingTimeout) clearTimeout(loadingTimeout);
      })
    },
    //实时同步信息
    get_sync_file() {
      // 获取重传信息
      this.getRetransmissionInfo();
      
      // 模拟数据开关，设为true启用模拟数据，false则使用真实接口
      const useMockData = false;
      
      // 模拟数据 - 可随时通过注释或修改上面的useMockData变量切换
      if (useMockData) {
        // 生成动态变化的数据
        const randomSpeed1 = (Math.random() * 10 + 5).toFixed(2); // 5-15MB/s之间
        const randomSpeed2 = (Math.random() * 8 + 2).toFixed(2);  // 2-10MB/s之间
        const randomRate1 = (Math.random() * 0.9 + 0.1).toFixed(2); // 10%-100%之间
        const randomRate2 = (Math.random() * 0.6 + 0.1).toFixed(2); // 10%-70%之间
        
        // 模拟待同步文件数量波动
        const pendingBase = this.gras4PendingCount || 45;
        const pendingChange = Math.floor(Math.random() * 5) - 2; // -2到+2的变化
        const newPending = Math.max(1, pendingBase + pendingChange);
        
        // 模拟错误数量和等待数量变化
        const waitCount = Math.floor(Math.random() * 3) + 1;
        const errorCount = Math.floor(Math.random() * 2) + 1;
        
        // 模拟的响应数据
        const mockResponse = {
          data: {
            code: 200,
            stat_res: {
              GRAS3: {
                DONE: 42,
                ERROR: 1,
                WAIT: 3
              },
              GRAS4: {
                DO: 1, 
                DONE: 102,
                ERROR: errorCount,
                WAIT: waitCount,
                WRITE: newPending - waitCount - errorCount
              },
              GRAS5: {
                ERROR: 1,
                WAIT: 5,
                WRITE: 2
              }
            },
            stat_speed: [
              {
                real_speed: randomSpeed1,
                real_rate: randomRate1,
                fileName: "TW2_Ast_GRAS3_20250424172207_00001-001_01_01_00008.gras",
                gras: "GRAS3"
              },
              {
                real_speed: randomSpeed2,
                real_rate: randomRate2,
                fileName: "TW2_Ast_GRAS4_20250425083012_00002-001_01_01_00015.gras",
                gras: "GRAS4"
              },
              // GRAS5不传输，保持等待状态
            ]
          }
        };
        
        // 处理模拟数据，复用现有的处理逻辑
        this.handleSyncFileResponse(mockResponse);
        return;
      }
      
      // 实际接口调用
      this.$axios({
        method: "post",
        url: DMSip + '/-/bin.preData.get_sync_file',
      }).then((res) => {
        // 调用统一的处理方法
        this.handleSyncFileResponse(res);
      }).catch(error => {
        console.error('获取同步数据失败:', error)
        this.$message.error('获取同步数据失败')
      })
    },
    
    // 提取处理响应数据的逻辑为单独方法，以便复用
    handleSyncFileResponse(res) {
      if (res.data) {
        try {
          // 获取当前时间
          const currentTime = moment().format('YYYY-MM-DD HH:mm:ss');

          // 记录之前的同步状态
          const prevGras3IsSyncing = this.gras3IsSyncing;
          const prevGras4IsSyncing = this.gras4IsSyncing;
          const prevGras5IsSyncing = this.gras5IsSyncing;
          
          // 处理stat_res数据（天线状态信息）
          if (res.data.stat_res) {
            // 处理GRAS3状态
            this.gras3Stats = res.data.stat_res.GRAS3 || {};
            // 计算GRAS3待同步文件数
            this.gras3PendingCount = 0;
            // 累加除DONE以外的所有状态数量
            if (this.gras3Stats) {
              Object.keys(this.gras3Stats).forEach(status => {
                if (status !== 'DONE' && typeof this.gras3Stats[status] === 'number') {
                  this.gras3PendingCount += this.gras3Stats[status];
                }
              });
            }
            
            // 处理GRAS4状态
            this.gras4Stats = res.data.stat_res.GRAS4 || {};
            // 计算GRAS4待同步文件数
            this.gras4PendingCount = 0;
            // 累加除DONE以外的所有状态数量
            if (this.gras4Stats) {
              Object.keys(this.gras4Stats).forEach(status => {
                if (status !== 'DONE' && typeof this.gras4Stats[status] === 'number') {
                  this.gras4PendingCount += this.gras4Stats[status];
                }
              });
            }
            
            // 处理GRAS5状态
            this.gras5Stats = res.data.stat_res.GRAS5 || {};
            // 计算GRAS5待同步文件数
            this.gras5PendingCount = 0;
            // 累加除DONE以外的所有状态数量
            if (this.gras5Stats) {
              Object.keys(this.gras5Stats).forEach(status => {
                if (status !== 'DONE' && typeof this.gras5Stats[status] === 'number') {
                  this.gras5PendingCount += this.gras5Stats[status];
                }
              });
            }
          }
          
          // 处理stat_speed数据（实时同步信息）
          if (Array.isArray(res.data.stat_speed)) {
            // 重置所有天线的同步状态
            this.gras3IsSyncing = false;
            this.gras4IsSyncing = false;
            this.gras5IsSyncing = false;
            this.gras3RealSync = '-';
            this.gras4RealSync = '-';
            this.gras5RealSync = '-';
            
            // 遍历实时同步数据
            res.data.stat_speed.forEach(syncData => {
              if (syncData && syncData.gras) {
                // 根据gras字段区分天线
                switch(syncData.gras) {
                  case 'GRAS3':
                    this.gras3IsSyncing = true;
                    this.gras3RealSync = syncData.fileName || '-';
                    
                    // 更新GRAS3速度和进度
                    const gras3Speed = parseFloat(parseFloat(syncData.real_speed || 0).toFixed(2)) || 0;
                    this.gras3SpeedHistory.push(gras3Speed);
                    this.gras3TimeHistory.push(currentTime);
                    if (this.gras3SpeedHistory.length > this.maxSpeedPoints) {
                      this.gras3SpeedHistory.shift();
                      this.gras3TimeHistory.shift();
                    }
                    
                    // 更新GRAS3图表数据
                    this.optionGras3.series[0].data = [...this.gras3SpeedHistory];
                    this.optionGras3.xAxis.data = [...this.gras3TimeHistory];
                    
                    // 动态调整Y轴最大值
                    const maxSpeed3 = Math.max(...this.gras3SpeedHistory);
                    this.optionGras3.yAxis.max = Math.ceil(maxSpeed3 * 1.2); // 留出20%的余量
                    
                    // 更新GRAS3进度条
                    this.gras3SyncProgress = parseFloat(syncData.real_rate || 0) * 100 || 0;
                    break;
                    
                  case 'GRAS4':
                    this.gras4IsSyncing = true;
                    this.gras4RealSync = syncData.fileName || '-';
                    
                    // 更新GRAS4速度和进度
                    const gras4Speed = parseFloat(parseFloat(syncData.real_speed || 0).toFixed(2)) || 0;
                    this.gras4SpeedHistory.push(gras4Speed);
                    this.gras4TimeHistory.push(currentTime);
                    if (this.gras4SpeedHistory.length > this.maxSpeedPoints) {
                      this.gras4SpeedHistory.shift();
                      this.gras4TimeHistory.shift();
                    }
                    
                    // 更新GRAS4图表数据
                    this.optionGras4.series[0].data = [...this.gras4SpeedHistory];
                    this.optionGras4.xAxis.data = [...this.gras4TimeHistory];
                    
                    // 动态调整Y轴最大值
                    const maxSpeed4 = Math.max(...this.gras4SpeedHistory);
                    this.optionGras4.yAxis.max = Math.ceil(maxSpeed4 * 1.2); // 留出20%的余量
                    
                    // 更新GRAS4进度条
                    this.gras4SyncProgress = parseFloat(syncData.real_rate || 0) * 100 || 0;
                    break;
                    
                  case 'GRAS5':
                    this.gras5IsSyncing = true;
                    this.gras5RealSync = syncData.fileName || '-';
                    
                    // 更新GRAS5速度和进度
                    const gras5Speed = parseFloat(parseFloat(syncData.real_speed || 0).toFixed(2)) || 0;
                    this.gras5SpeedHistory.push(gras5Speed);
                    this.gras5TimeHistory.push(currentTime);
                    if (this.gras5SpeedHistory.length > this.maxSpeedPoints) {
                      this.gras5SpeedHistory.shift();
                      this.gras5TimeHistory.shift();
                    }
                    
                    // 更新GRAS5图表数据
                    this.optionGras5.series[0].data = [...this.gras5SpeedHistory];
                    this.optionGras5.xAxis.data = [...this.gras5TimeHistory];
                    
                    // 动态调整Y轴最大值
                    const maxSpeed5 = Math.max(...this.gras5SpeedHistory);
                    this.optionGras5.yAxis.max = Math.ceil(maxSpeed5 * 1.2); // 留出20%的余量
                    
                    // 更新GRAS5进度条
                    this.gras5SyncProgress = parseFloat(syncData.real_rate || 0) * 100 || 0;
                    break;
                    
                  default:
                    console.warn('未知天线类型:', syncData.gras);
                }
              }
            });
            
            // 对于未同步的天线，清空数据
            if (!this.gras3IsSyncing) {
              this.gras3SpeedHistory = new Array(this.maxSpeedPoints).fill(0);
              this.gras3TimeHistory = new Array(this.maxSpeedPoints).fill('');
              this.optionGras3.series[0].data = [...this.gras3SpeedHistory];
              this.optionGras3.xAxis.data = [...this.gras3TimeHistory];
              this.gras3SyncProgress = 0;
            }
            
            if (!this.gras4IsSyncing) {
              this.gras4SpeedHistory = new Array(this.maxSpeedPoints).fill(0);
              this.gras4TimeHistory = new Array(this.maxSpeedPoints).fill('');
              this.optionGras4.series[0].data = [...this.gras4SpeedHistory];
              this.optionGras4.xAxis.data = [...this.gras4TimeHistory];
              this.gras4SyncProgress = 0;
            }
            
            if (!this.gras5IsSyncing) {
              this.gras5SpeedHistory = new Array(this.maxSpeedPoints).fill(0);
              this.gras5TimeHistory = new Array(this.maxSpeedPoints).fill('');
              this.optionGras5.series[0].data = [...this.gras5SpeedHistory];
              this.optionGras5.xAxis.data = [...this.gras5TimeHistory];
              this.gras5SyncProgress = 0;
            }
          }

          // 检查同步状态变化并更新历史数据
          if ((prevGras3IsSyncing && !this.gras3IsSyncing) || 
              (prevGras4IsSyncing && !this.gras4IsSyncing) ||
              (prevGras5IsSyncing && !this.gras5IsSyncing)) {
            // 延迟1秒后更新历史数据，确保后端数据已更新
            setTimeout(() => {
              this.get_file_stat();
            }, 1000);
          }

          // 更新图表显示
          this.updateCharts();

          // 检查是否需要显示警告
          this.checkSyncWarning()
        } catch (error) {
          console.error('处理同步数据时出错:', error)
          this.$message.error('处理同步数据时出错')
        }
      } else {
        console.error('返回数据格式错误:', res.data)
        this.$message.error('获取同步数据失败')
      }
    },
    
    // 更新所有图表
    updateCharts() {
      // 初始化或更新GRAS3图表
      const chartDom3 = document.getElementById('echartsGras3');
      if (chartDom3) {
        if (!this.myChartGras3) {
          this.myChartGras3 = echarts.init(chartDom3);
        }
        this.myChartGras3.setOption(this.optionGras3);
      }
      
      // 初始化或更新GRAS4图表
      const chartDom4 = document.getElementById('echartsGras4');
      if (chartDom4) {
        if (!this.myChartGras4) {
          this.myChartGras4 = echarts.init(chartDom4);
        }
        this.myChartGras4.setOption(this.optionGras4);
      }
      
      // 初始化或更新GRAS5图表
      const chartDom5 = document.getElementById('echartsGras5');
      if (chartDom5) {
        if (!this.myChartGras5) {
          this.myChartGras5 = echarts.init(chartDom5);
        }
        this.myChartGras5.setOption(this.optionGras5);
      }
    },
    // 检查同步数据是否需要显示警告
    checkSyncWarning() {
      const warningThreshold = 1000 // 设置警告阈值
      if (this.gras3PendingCount > warningThreshold) {
        this.$message.warning(`GRAS3待同步文件数量较多: ${this.gras3PendingCount}`)
      }
      if (this.gras4PendingCount > warningThreshold) {
        this.$message.warning(`GRAS4待同步文件数量较多: ${this.gras4PendingCount}`)
      }
      if (this.gras5PendingCount > warningThreshold) {
        this.$message.warning(`GRAS5待同步文件数量较多: ${this.gras5PendingCount}`)
      }
    },
    //磁盘空间监视
    get_hard_disk_storage() {
      this.$axios({
        method: "post",
        url: DMSip + '/-/bin.preData.get_hard_disk_storage',
      }).then((res) => {
        if (res.data && Array.isArray(res.data.data) && res.data.data.length >= 3) {
          try {
            // 密云站数据
            if (res.data.data[1] && typeof res.data.data[1].rate === 'number') {
              this.mycppath = res.data.data[1].path || '未知路径'
              this.mycpkj = this.formatRate(res.data.data[1].rate)
            } else {
              console.error('密云站数据格式错误:', res.data.data[1])
              this.mycppath = '数据错误'
              this.mycpkj = 0
            }

            // 武清站数据
            if (res.data.data[0] && typeof res.data.data[0].rate === 'number') {
              this.wqcppath = res.data.data[0].path || '未知路径'
              this.wqcpkj = this.formatRate(res.data.data[0].rate)
            } else {
              console.error('武清站数据格式错误:', res.data.data[0])
              this.wqcppath = '数据错误'
              this.wqcpkj = 0
            }

            // 总部数据
            if (res.data.data[2] && typeof res.data.data[2].rate === 'number') {
              this.zbcppath = res.data.data[2].path || '未知路径'
              this.zbcpkj = this.formatRate(res.data.data[2].rate)
            } else {
              console.error('总部数据格式错误:', res.data.data[2])
              this.zbcppath = '数据错误'
              this.zbcpkj = 0
            }
          } catch (error) {
            console.error('处理磁盘空间数据时出错:', error)
            this.$message.error('处理磁盘空间数据时出错')
          }
        } else {
          console.error('返回数据格式错误:', res.data)
          this.$message.error('获取磁盘空间数据失败')
        }
      }).catch(error => {
        console.error('获取磁盘空间数据失败:', error)
        this.$message.error('获取磁盘空间数据失败')
      })
    },
    // 格式化磁盘使用率
    formatRate(rate) {
      // 确保rate在0-100之间
      const validRate = Math.max(0, Math.min(100, rate))
      // 保留两位小数
      return Number(validRate.toFixed(2))
    },
    // 获取进程状态
    get_pro_status() {
      this.$axios({
        method: "post",
        url: DMSip + '/-/bin.preData.get_pro_status',
      }).then((res) => {
        if (res.data && typeof res.data.total_seconds === 'number') {
          try {
            this.timeStartSeconds = res.data.total_seconds

            // 设置初始时间显示
            const d = moment.duration(this.timeStartSeconds, 'seconds');
            this.H = Math.floor(this.timeStartSeconds / 3600)
            this.M = d.minutes()
            this.S = d.seconds()

            // 关键：每次校准都重置本地计时器和已用秒数
            if (this.timeUpdateTimer) {
              clearInterval(this.timeUpdateTimer)
              this.timeUpdateTimer = null
            }
            this.timeRunning = false
            this.elapsedSeconds = 0 // 新增：重置本地已用秒数
            this.startTimeUpdate() // 重新启动本地计时器

          } catch (error) {
            console.error('时间转换错误:', error)
            this.$message.error('时间数据格式错误')
          }
        } else {
          console.error('返回数据格式错误:', res.data)
          this.$message.error('获取进程状态失败')
        }
      }).catch(error => {
        console.error('获取进程状态失败:', error)
        this.$message.error('获取进程状态失败')
      })
    },
    // 启动时间更新
    startTimeUpdate() {
      // 避免重复创建定时器
      if (this.timeRunning) return
      this.timeRunning = true
      // let elapsedSeconds = 0 // 删除原有局部变量
      this.timeUpdateTimer = setInterval(() => {
        this.elapsedSeconds++ // 用data属性
        const totalSeconds = this.timeStartSeconds + this.elapsedSeconds
        const d = moment.duration(totalSeconds, 'seconds')
        // 正确写法
        this.H = Math.floor(totalSeconds / 3600)
        this.M = d.minutes()
        this.S = d.seconds()
      }, 1000)
    },
    echartsInit() {
      const chartDom = document.getElementById('echarts');
      const myChart = echarts.init(chartDom);
      myChart.setOption(this.option);
      // 保存图表实例，以便在watch中更新
      this.myChart = myChart;
      
      // 添加事件监听器，使用passive选项
      const resizeHandler = () => {
        myChart.resize();
      };
      
      window.addEventListener('resize', resizeHandler, { passive: true });
      window.addEventListener('mousewheel', resizeHandler, { passive: true });
      window.addEventListener('touchmove', resizeHandler, { passive: true });
      
      // 保存事件监听器引用，以便在组件销毁时移除
      this.resizeHandler = resizeHandler;
    },
    initGrasCharts() {
      // 初始化GRAS3图表
      const chartDom3 = document.getElementById('echartsGras3');
      if (chartDom3) {
        if (!this.myChartGras3) {
          this.myChartGras3 = echarts.init(chartDom3);
        }
        this.myChartGras3.setOption(this.optionGras3);
        
        // 添加点击事件监听
        this.myChartGras3.getZr().on('click', () => {
          this.chartGras3DialogVisible = true;
          this.$nextTick(() => {
            const largeDom = document.getElementById('echartsGras3-large');
            if (!largeDom) return;
            
            if (!this.chartGras3Large) {
              this.chartGras3Large = echarts.init(largeDom);
            }
            // 设置放大图表的配置
            const largeOption = JSON.parse(JSON.stringify(this.optionGras3));
            // 调整放大后的图表样式
            largeOption.grid = {
              top: 50,
              left: 80,
              right: 50,
              bottom: 50
            };
            this.chartGras3Large.setOption(largeOption);
            this.chartGras3Large.resize();
          });
        });
      }
      
      // 初始化GRAS4图表
      const chartDom4 = document.getElementById('echartsGras4');
      if (chartDom4) {
        if (!this.myChartGras4) {
          this.myChartGras4 = echarts.init(chartDom4);
        }
        this.myChartGras4.setOption(this.optionGras4);
        
        // 添加点击事件监听
        this.myChartGras4.getZr().on('click', () => {
          this.chartGras4DialogVisible = true;
          this.$nextTick(() => {
            const largeDom = document.getElementById('echartsGras4-large');
            if (!largeDom) return;
            
            if (!this.chartGras4Large) {
              this.chartGras4Large = echarts.init(largeDom);
            }
            // 设置放大图表的配置
            const largeOption = JSON.parse(JSON.stringify(this.optionGras4));
            // 调整放大后的图表样式
            largeOption.grid = {
              top: 50,
              left: 80,
              right: 50,
              bottom: 50
            };
            this.chartGras4Large.setOption(largeOption);
            this.chartGras4Large.resize();
          });
        });
      }
      
      // 初始化GRAS5图表
      const chartDom5 = document.getElementById('echartsGras5');
      if (chartDom5) {
        if (!this.myChartGras5) {
          this.myChartGras5 = echarts.init(chartDom5);
        }
        this.myChartGras5.setOption(this.optionGras5);
        
        // 添加点击事件监听
        this.myChartGras5.getZr().on('click', () => {
          this.chartGras5DialogVisible = true;
          this.$nextTick(() => {
            const largeDom = document.getElementById('echartsGras5-large');
            if (!largeDom) return;
            
            if (!this.chartGras5Large) {
              this.chartGras5Large = echarts.init(largeDom);
            }
            // 设置放大图表的配置
            const largeOption = JSON.parse(JSON.stringify(this.optionGras5));
            // 调整放大后的图表样式
            largeOption.grid = {
              top: 50,
              left: 80,
              right: 50,
              bottom: 50
            };
            this.chartGras5Large.setOption(largeOption);
            this.chartGras5Large.resize();
          });
        });
      }
    },
    // 显示同步详情对话框
    showSyncDetails() {
      this.syncDetailsDialogVisible = true
      this.syncDetailsDateRange = this.value1 // 使用主图表相同的日期范围
      this.syncDetailsStationFilter = this.radio4 // 使用主图表相同的天线筛选
      this.syncDetailsPagination.currentPage = 1
      this.getSyncFileDetails()
    },
    // 获取同步文件详情数据
    getSyncFileDetails() {
      this.syncDetailsLoading = true
      
      let params = {
        sd: '',
        ed: '',
        sta: this.syncDetailsStationFilter == '0' ? '' : this.syncDetailsStationFilter,
        page: this.syncDetailsPagination.currentPage,
        ps: this.syncDetailsPagination.pageSize,
        col: this.syncDetailsSortCol,
        sort: this.syncDetailsSortOrder
      }

      // 处理日期
      if (this.syncDetailsDateRange && this.syncDetailsDateRange.length === 2) {
        params.sd = moment(this.syncDetailsDateRange[0]).format('YYYY-MM-DD')
        params.ed = moment(this.syncDetailsDateRange[1]).format('YYYY-MM-DD')
      } else {
        // 使用默认日期范围
        const endDate = moment()
        const startDate = moment().subtract(6, 'days')
        params.sd = startDate.format('YYYY-MM-DD')
        params.ed = endDate.format('YYYY-MM-DD')
        this.syncDetailsDateRange = [startDate.toDate(), endDate.toDate()]
      }

      this.$axios({
        method: "post",
        url: DMSip + '/-/bin.preData.get_sync_file_data',
        data: JSON.stringify(params),
      }).then(res => {
        if (res.data && res.data.code === 200) {
          this.syncDetailsData = res.data.data || []
          // 修改这里：确保从响应中正确获取总数
          this.syncDetailsPagination.total = parseInt(res.data.total || 0)
        } else {
          this.$message.warning('获取同步文件详情失败')
        }
      }).catch(error => {
        console.error('获取同步文件详情失败:', error)
        this.$message.error('获取同步文件详情失败')
      }).finally(() => {
        this.syncDetailsLoading = false
      })
    },
    // 处理分页变化
    handleSyncDetailsPageChange(page) {
      this.syncDetailsPagination.currentPage = page
      this.getSyncFileDetails()
    },
    // 处理每页条数变化
    handleSyncDetailsSizeChange(size) {
      this.syncDetailsPagination.pageSize = size
      this.syncDetailsPagination.currentPage = 1
      this.getSyncFileDetails()
    },
    // 处理站点筛选变化
    handleSyncDetailsStationChange() {
      this.syncDetailsPagination.currentPage = 1
      this.getSyncFileDetails()
    },
    // 处理日期范围变化
    handleSyncDetailsDateChange() {
      // 验证日期范围是否超过7天
      if (this.syncDetailsDateRange && this.syncDetailsDateRange.length === 2) {
        const [start, end] = this.syncDetailsDateRange
        const diffTime = end - start
        const diffDays = diffTime / (1000 * 60 * 60 * 24)
        
        if (diffDays > 7) {
          this.$message.warning("日期范围不能超过7天，已自动调整为最近7天")
          // 自动调整为最近7天
          const endDate = new Date()
          const startDate = new Date()
          startDate.setDate(endDate.getDate() - 6)
          this.syncDetailsDateRange = [startDate, endDate]
        }
      }
      this.syncDetailsPagination.currentPage = 1
      this.getSyncFileDetails()
    },
    // 格式化状态显示
    formatSyncStatus(status) {
      const statusMap = {
        'DONE': '成功',
        'FAIL': '失败',
        'PROCESSING': '进行中',
        'PENDING': '等待中',
        'DO': '正在拷贝',
        'WAIT': '等待中',
        'ERROR': '失败'
      }
      return statusMap[status] || status
    },
    // 格式化站点显示
    formatStationName(station) {
      const stationMap = {
        'MY': '密云站',
        'WQ': '武清站'
      }
      return stationMap[station] || station
    },
    // 格式化文件大小
    formatFileSize(size) {
      if (!size && size !== 0) return '--'
      
      // 确保size是数字类型
      const numSize = Number(size)
      if (isNaN(numSize)) return '--'
      
      const units = ['B', 'KB', 'MB', 'GB', 'TB']
      let fileSize = numSize
      let unitIndex = 0
      
      while (fileSize >= 1024 && unitIndex < units.length - 1) {
        fileSize /= 1024
        unitIndex++
      }
      
      return fileSize.toFixed(2) + ' ' + units[unitIndex]
    },
    // 清理数据
    cleanData(station) {
      // 检查权限
      if (!checkPermission('clean_data')) {
        // 未登录，显示确认提示框
        this.$confirm('该操作需要登录权限，是否跳转到登录页面？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 用户确认，跳转到登录页面
          this.$router.push({
            path: '/login',
            query: { redirect: this.$route.fullPath }
          });
        }).catch(() => {
          // 用户取消，不做任何操作
          this.$message.info('已取消操作');
        });
        return;
      }
      
      let stationMap = {
        '密云站': 'MY',
        '武清站': 'WQ',
        '总部': 'ZB'
      }
      
      this.$confirm(`确定要清理${station}的数据吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios({
          method: "post",
          url: DMSip + '/-/bin.preData.clean_data',
          data: JSON.stringify({
            sta: stationMap[station]
          })
        }).then(res => {
          if (res.data && res.data.code === 200) {
            this.$message.success('清理成功')
            // 清理成功后刷新数据
            this.get_hard_disk_storage()
          } else {
            this.$message.error('清理失败')
          }
        }).catch(error => {
          console.error('清理数据失败:', error)
          this.$message.error('清理数据失败')
        })
      }).catch(() => {
        this.$message.info('已取消清理')
      })
    },
    handleResize() {
      // 重新调整所有图表大小
      if (this.myChart) {
        this.myChart.resize();
      }
      if (this.myChartGras3) {
        this.myChartGras3.resize();
      }
      if (this.myChartGras4) {
        this.myChartGras4.resize();
      }
      if (this.myChartGras5) {
        this.myChartGras5.resize();
      }
      // 处理大图表的调整
      if (this.chartGras3Large && this.chartGras3DialogVisible) {
        this.chartGras3Large.resize();
      }
      if (this.chartGras4Large && this.chartGras4DialogVisible) {
        this.chartGras4Large.resize();
      }
      if (this.chartGras5Large && this.chartGras5DialogVisible) {
        this.chartGras5Large.resize();
      }
    },
    showStatusDetails(status, station, value) {
      this.statusDetailsDialogVisible = true
      this.statusDetailsStationFilter = station
      this.statusDetailsDateRange = this.value1
      this.statusDetailsPagination.currentPage = 1
      // 设置对话框标题
      const statusText = status === 'DONE' ? '完成' : status === 'ERROR' ? '错误' : '等待'
      this.statusDialogTitle = `${station} - ${statusText}文件列表 (共${value}个)`
      
      this.getStatusDetails(status, value)
    },
    getStatusDetails(status, value) {
      this.statusDetailsLoading = true
      
      // 从对话框标题中获取当前天线
      const currentStatus = this.getCurrentStatusFromTitle()
      if (!currentStatus) return
      
      let params = {
        status: status,
        gras: currentStatus.station,
        page: this.statusDetailsPagination.currentPage,
        ps: this.statusDetailsPagination.pageSize
      }

      // 处理日期
      if (this.statusDetailsDateRange && this.statusDetailsDateRange.length === 2) {
        params.sd = moment(this.statusDetailsDateRange[0]).format('YYYY-MM-DD')
        params.ed = moment(this.statusDetailsDateRange[1]).format('YYYY-MM-DD')
      } else {
        // 使用默认日期范围
        const endDate = moment()
        const startDate = moment().subtract(6, 'days')
        params.sd = startDate.format('YYYY-MM-DD')
        params.ed = endDate.format('YYYY-MM-DD')
        this.statusDetailsDateRange = [startDate.toDate(), endDate.toDate()]
      }

      this.$axios({
        method: "post",
        url: DMSip + '/-/bin.preData.get_status_file_data',
        data: JSON.stringify(params),
      }).then(res => {
        if (res.data && res.data.code === 200) {
          this.statusDetailsData = res.data.data || []
          // 修改这里：确保从响应中正确获取总数，并使用传入的value作为备选
          this.statusDetailsPagination.total = parseInt(res.data.total || value || 0)
        } else {
          this.$message.warning('获取状态文件详情失败')
        }
      }).catch(error => {
        console.error('获取状态文件详情失败:', error)
        this.$message.error('获取状态文件详情失败')
      }).finally(() => {
        this.statusDetailsLoading = false
      })
    },
    handleStatusDetailsPageChange(page) {
      this.statusDetailsPagination.currentPage = page
      // 重新获取当前状态的数据
      const currentStatus = this.getCurrentStatusFromTitle()
      if (currentStatus) {
        this.getStatusDetails(currentStatus.status, currentStatus.value)
      }
    },
    handleStatusDetailsSizeChange(size) {
      this.statusDetailsPagination.pageSize = size
      this.statusDetailsPagination.currentPage = 1
      // 重新获取当前状态的数据
      const currentStatus = this.getCurrentStatusFromTitle()
      if (currentStatus) {
        this.getStatusDetails(currentStatus.status, currentStatus.value)
      }
    },
    // 从对话框标题中获取当前状态和值
    getCurrentStatusFromTitle() {
      if (!this.statusDialogTitle) return null
      
      const match = this.statusDialogTitle.match(/^(GRAS\d) - (完成|错误|等待)文件列表 \(共(\d+)个\)$/)
      if (!match) return null
      
      const [, station, statusText, value] = match
      const status = statusText === '完成' ? 'DONE' : statusText === '错误' ? 'ERROR' : 'WAIT'
      
      return {
        station,
        status,
        value: parseInt(value)
      }
    },
    // 获取重传文件信息
    getRetransmissionInfo() {
      this.$axios({
        method: "post",
        url: DMSip + '/-/bin.preData.get_retransmission_file',
      }).then((res) => {
        if (res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
          // 重置重传状态
          this.gras3Retransmission = null;
          this.gras4Retransmission = null;
          this.gras5Retransmission = null;
          
          // 处理返回数据
          res.data.data.forEach(item => {
            switch(item.gras) {
              case 'GRAS3':
                this.gras3Retransmission = item;
                break;
              case 'GRAS4':
                this.gras4Retransmission = item;
                break;
              case 'GRAS5':
                this.gras5Retransmission = item;
                break;
            }
          });
        }
      }).catch(error => {
        console.error('获取重传文件信息失败:', error);
      });
    },

    // 显示重传详情
    showRetransmissionDetails(station, data) {
      this.currentRetransmissionGras = station;
      this.retransmissionDialogVisible = true;
      this.retransmissionPagination.currentPage = 1;
      // 新增：保存总数和已完成数
      this.retransmissionTotal = data.t || 0;
      this.retransmissionDone = data.dt || 0;
      this.getRetransmissionFileList();
    },
    
    // 获取重传文件列表
    getRetransmissionFileList() {
      this.retransmissionLoading = true;
      const params = {
        page: this.retransmissionPagination.currentPage.toString(),
        ps: this.retransmissionPagination.pageSize.toString(),
        gras: this.currentRetransmissionGras
      };
      this.$axios({
        method: "post",
        url: DMSip + '/-/bin.preData.get_retransmission_file_list',
        data: JSON.stringify(params),
      }).then(res => {
        if (res.data && res.data.code === 200) {
          this.retransmissionData = res.data.data || [];
          // 只用于分页
          this.retransmissionPagination.total = parseInt(res.data.total || this.retransmissionTotal || 0);

          // 新增：自动从数据中提取datestr并更新标题
          let datestr = '';
          if (this.retransmissionData.length > 0 && this.retransmissionData[0].datestr) {
            datestr = this.formatDateStr(this.retransmissionData[0].datestr);
          }
          // 这里直接用this.retransmissionTotal和this.retransmissionDone
          let dateStrText = datestr ? `, 重传时间: ${datestr}` : '';
          this.retransmissionDialogTitle = `${this.currentRetransmissionGras} - 重传文件列表 (总数: ${this.retransmissionTotal}, 已完成: ${this.retransmissionDone}${dateStrText})`;
        } else {
          this.$message.warning('获取重传文件列表失败');
        }
      }).catch(error => {
        console.error('获取重传文件列表失败:', error);
        this.$message.error('获取重传文件列表失败');
      }).finally(() => {
        this.retransmissionLoading = false;
      });
    },
    
    // 处理重传文件列表分页大小变化
    handleRetransmissionSizeChange(size) {
      this.retransmissionPagination.pageSize = size;
      this.retransmissionPagination.currentPage = 1;
      this.getRetransmissionFileList();
    },
    
    // 处理重传文件列表页码变化
    handleRetransmissionPageChange(page) {
      this.retransmissionPagination.currentPage = page;
      this.getRetransmissionFileList();
    },
    
    // 格式化日期字符串
    formatDateStr(datestr) {
      if (!datestr) return '--';
      return moment(datestr, 'YYYYMMDDHHmmss').format('YYYY-MM-DD HH:mm:ss');
    },
    // 处理清理重传文件列表
    handleCleanRetransmission() {
      // 检查权限
      if (!checkPermission('clean_data')) {
        // 未登录，显示确认提示框
        this.$confirm('该操作需要登录权限，是否跳转到登录页面？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 用户确认，跳转到登录页面
          this.$router.push({
            path: '/login',
            query: { redirect: this.$route.fullPath }
          });
        }).catch(() => {
          // 用户取消，不做任何操作
          this.$message.info('已取消操作');
        });
        return;
      }

      // 显示确认对话框
      this.$confirm(`确定要清理${this.currentRetransmissionGras}的重传文件列表吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户确认，发送清理请求
        this.$axios({
          method: "post",
          url: DMSip + '/-/bin.preData.clean_retransmission_file_list',
          data: JSON.stringify({
            gras: this.currentRetransmissionGras
          })
        }).then(res => {
          if (res.data && res.data.code === 200) {
            this.$message.success('重传列表清理成功');
            // 刷新重传文件列表
            this.getRetransmissionFileList();
            // 刷新重传状态信息
            this.getRetransmissionInfo();
          } else {
            this.$message.error(res.data.msg || '清理失败');
          }
        }).catch(error => {
          console.error('清理重传文件列表失败:', error);
          this.$message.error('清理重传文件列表失败');
        });
      }).catch(() => {
        this.$message.info('已取消清理');
      });
    },
    // 处理排序事件（历史同步详情-同步结果列）
    handleSyncDetailsSortChange({ prop, order }) {
      // prop 是字段名，order 是 'ascending' 或 'descending'
      if (order) {
        this.syncDetailsSortCol = prop;
        this.syncDetailsSortOrder = order === 'ascending' ? 'asc' : 'desc';
      } else {
        // 如果没有排序，清空
        this.syncDetailsSortCol = '';
        this.syncDetailsSortOrder = '';
      }
      this.getSyncFileDetails();
    },
    // 添加新的处理方法
    handleCleanClick(station, usage) {
      if (usage < 90) {
        this.$message.warning('未达到清理条件（空间使用率需达到90%）');
        return;
      }
      this.cleanData(station);
    },
    // 新增：获取天线联网状态
    get_ping_status() {
      this.$axios({
        method: "post",
        url: DMSip + '/-/bin.preData.get_ping_status',
      }).then((res) => {
        if (res.data && res.data.code === 200 && Array.isArray(res.data.status)) {
          try {
            // 默认状态设为在线（true）
            this.gras3Online = true
            this.gras4Online = true
            this.gras5Online = true
            // 处理返回的状态数据
            res.data.status.forEach(item => {
              if (item.hasOwnProperty('GRAS3')) {
                this.gras3Online = item.GRAS3 === true
              } else if (item.hasOwnProperty('GRAS4')) {
                this.gras4Online = item.GRAS4 === true
              } else if (item.hasOwnProperty('GRAS5')) {
                this.gras5Online = item.GRAS5 === true
              }
            })
            // 天线状态改变时发出通知（不弹窗，只在卡片上显示）
            // 这里不再使用this.$notify或this.$message
          } catch (error) {
            // 只打印错误，不弹窗
            console.error('处理天线联网状态数据时出错:', error)
          }
        } else {
          // 只打印错误，不弹窗
          console.error('获取天线联网状态返回数据格式错误:', res.data)
        }
      }).catch(error => {
        // 只打印错误，不弹窗
        console.error('获取天线联网状态失败:', error)
      })
    },
    handleCleanWaitList() {
      // 检查权限
      if (!checkPermission('clean_data')) {
        this.$confirm('该操作需要登录权限，是否跳转到登录页面？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.push({
            path: '/login',
            query: { redirect: this.$route.fullPath }
          });
        }).catch(() => {
          this.$message.info('已取消操作');
        });
        return;
      }

      // 获取当前天线
      const currentStatus = this.getCurrentStatusFromTitle();
      if (!currentStatus) return;
      const gras = currentStatus.station;

      // 确认弹窗
      this.$confirm(`确定要清理${gras}的等待文件列表吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用接口
        this.$axios({
          method: "post",
          url: DMSip + '/-/bin.preData.delete_wait_file_by_gras',
          data: JSON.stringify({ gras })
        }).then(res => {
          if (res.data && res.data.code === 200) {
            this.$message.success('等待列表清理成功');
            // 刷新等待文件列表
            this.getStatusDetails('WAIT', currentStatus.value);
          } else {
            this.$message.error(res.data.msg || '清理失败');
          }
        }).catch(error => {
          console.error('清理等待文件列表失败:', error);
          this.$message.error('清理等待文件列表失败');
        });
      }).catch(() => {
        this.$message.info('已取消清理');
      });
    },
  },
  watch: {
    value1: {
      handler(newVal) {
        if (newVal && newVal.length === 2) {
          const [start, end] = newVal;
          const diffTime = end - start;
          const diffDays = diffTime / (1000 * 60 * 60 * 24);
          
          if (diffDays > 7) {
            this.$message.warning("日期范围不能超过7天，已自动调整为最近7天");
            // 自动调整为最近7天
            const endDate = new Date();
            const startDate = new Date();
            startDate.setDate(endDate.getDate() - 6);
            this.value1 = [startDate, endDate];
          } else {
            // 日期范围有效，触发数据获取
            this.get_file_stat();
          }
        }
      },
      deep: true
    },
    //观察option的变化
    option: {
      handler(newVal, oldVal) {
        if (this.myChart) {
          if (newVal) {
            this.myChart.setOption(newVal);
          } else {
            this.myChart.setOption(oldVal);
          }
        } else {
          this.echartsInit();
        }
      },
      deep: true //对象内部属性的监听，关键。
    },
    // 添加对话框关闭时的图表更新
    chartGras3DialogVisible(val) {
      if (val && this.chartGras3Large) {
        this.$nextTick(() => {
          this.chartGras3Large.resize();
        });
      }
    },
    chartGras4DialogVisible(val) {
      if (val && this.chartGras4Large) {
        this.$nextTick(() => {
          this.chartGras4Large.resize();
        });
      }
    },
    chartGras5DialogVisible(val) {
      if (val && this.chartGras5Large) {
        this.$nextTick(() => {
          this.chartGras5Large.resize();
        });
      }
    },
    
    // 监听optionGras3、optionGras4和optionGras5的变化，同步更新大图表
    optionGras3: {
      handler(newVal) {
        if (this.myChartGras3) {
          this.myChartGras3.setOption(newVal);
        }
        if (this.chartGras3Large && this.chartGras3DialogVisible) {
          const largeOption = JSON.parse(JSON.stringify(newVal));
          largeOption.grid = {
            top: 50,
            left: 80,
            right: 50,
            bottom: 50
          };
          this.chartGras3Large.setOption(largeOption);
        }
      },
      deep: true
    },
    optionGras4: {
      handler(newVal) {
        if (this.myChartGras4) {
          this.myChartGras4.setOption(newVal);
        }
        if (this.chartGras4Large && this.chartGras4DialogVisible) {
          const largeOption = JSON.parse(JSON.stringify(newVal));
          largeOption.grid = {
            top: 50,
            left: 80,
            right: 50,
            bottom: 50
          };
          this.chartGras4Large.setOption(largeOption);
        }
      },
      deep: true
    },
    optionGras5: {
      handler(newVal) {
        if (this.myChartGras5) {
          this.myChartGras5.setOption(newVal);
        }
        if (this.chartGras5Large && this.chartGras5DialogVisible) {
          const largeOption = JSON.parse(JSON.stringify(newVal));
          largeOption.grid = {
            top: 50,
            left: 80,
            right: 50,
            bottom: 50
          };
          this.chartGras5Large.setOption(largeOption);
        }
      },
      deep: true
    }
  },
  components: {
    navbar: () => import('./navbar.vue'),
  }
}
</script>

<style>
@import '../styles/home.scss';

/* 添加可点击状态标签的样式 */
.status-tag .el-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.status-tag .el-tag:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 添加状态详情对话框的样式 */
.sync-details-dialog {
  .el-dialog__body {
    padding: 10px 20px;
  }
  
  .pagination-container {
    padding: 15px 0;
    text-align: right;
  }

  .dialog-header-actions {
    margin-bottom: 15px;
    text-align: right;
  }
}

.clean-btn-disabled {
  opacity: 0.6;
  cursor: not-allowed !important;
}

/* 添加天线离线样式 */
.offline-card {
  position: relative;
  box-shadow: 0 0 8px 2px rgba(255, 0, 0, 0.3) !important;
  border: 1px solid #f56c6c !important;
}

.offline-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: repeating-linear-gradient(
    45deg,
    rgba(255, 0, 0, 0.05),
    rgba(255, 0, 0, 0.05) 10px,
    rgba(255, 0, 0, 0.08) 10px,
    rgba(255, 0, 0, 0.08) 20px
  );
  pointer-events: none;
  z-index: 1;
  border-radius: 4px;
}

.offline-tag {
  margin-left: 10px;
  animation: blink 1.5s infinite;
  font-weight: bold;
}

@keyframes blink {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}
</style>
